package com.mulanweb.utils;

import com.alibaba.druid.support.json.JSONUtils;
import com.mulanweb.api.module.model.wechat.AccessToken;
import com.mulanweb.db.common.Constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/9.
 */
public class WeiXinUtil {

    public void getUserDetail(String openId, String accessToken, String lang){
        StringBuilder json = new StringBuilder();
        try {
            URL urlObject = new URL(Constant.WeChatFinalValue.getGetUserDetailUrl(accessToken,openId,lang)) ;
            URLConnection uc = urlObject.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
            String inputLine = null;
            while ( (inputLine = in.readLine()) != null) {
                json.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String,String> access_token = jsonToMap(json.toString()) ;
        if(access_token.containsKey("access_token")){
            //return access_token.get("access_token") ;
        }else{
            //return null ;
        }
    }

    public static Map<String,String> jsonToMap(String json){
        if(json.startsWith("{") && json.endsWith("}")){
            json = json.substring(1,json.length()-1) ;
            String[] jsons = json.split(",") ;
            Map<String,String> result = new HashMap<String,String>();
            for(String para : jsons){
                String[] pp = para.split(":") ;
                if(pp.length == 2){
                    String key = pp[0].replace("\'","") ;
                    key = key.replace("\"","") ;
                    String value = pp[1].replace("\'","") ;
                    value = pp[1].replace("\"","") ;
                    result.put(key, value) ;
                }
            }
            return result ;
        }else{
            return null ;
        }
    }

     public void getXmlPara(){
         /*try {
             Document doc = Jsoup.parse(getRequest().getInputStream(), "UTF-8", "http://www.wechat.com");
             System.out.println(doc.body().html());
             doc.select("xml").first().children().forEach(e -> {
                 System.out.println(e.tagName() + " - " + e.text());
             });
         } catch (IOException e) {
             e.printStackTrace();
         }*/
     }

}
